package com.scb.dev.mms.service.impl;

import com.scb.dev.mms.common.DataCommon;
import com.scb.dev.mms.common.ResponseResult;
import com.scb.dev.mms.common.ResultType;
import com.scb.dev.mms.common.StatusCode;
import com.scb.dev.mms.dao.AccountMapper;
import com.scb.dev.mms.dao.EmployeeMapper;
import com.scb.dev.mms.dao.PositionMapper;
import com.scb.dev.mms.pojo.Position;
import com.scb.dev.mms.service.IPositionService;
import com.scb.dev.mms.util.DateTool;
import com.scb.dev.mms.util.UUIDTool;
import com.scb.dev.mms.vo.PositionInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName: PositionServiceImpl
 * Description: PositionService 业务实现类
 * Date: 2018/11/27 4:56 PM
 *
 * @author Dong,Yuchuan
 * @version V1.0
 * @since JDK 1.8
 */
@Slf4j
@Service
public class PositionServiceImpl implements IPositionService {

    @Resource
    private PositionMapper positionMapper;

    @Resource
    private AccountMapper accountMapper;

    /**
     * insertPosition: 添加新职位
     *
     * @param position  新职位对象
     * @return  操作成功: {true, "添加成功", 202}
     */
    @Override
    public ResponseResult insertPosition(Position position,String operatorId) {
        if (position == null || StringUtils.isBlank(operatorId)) {
            log.info("The parameter is empty and the position was added");
            return new ResponseResult(false, ResultType.PARAMETER_NULL, StatusCode.PARAMETERNULL);
        }
        if (positionMapper.checkPositionName(position.getPositionName()) > 0){
            log.info("The position already exists");
            return ResponseResult.resultError("The position already exists");
        }
        position.setPositionId(UUIDTool.generateUUID());
        position.setPositionCreatorAccountId(operatorId);
        if (positionMapper.insertSelective(position) == 0) {
            log.info("Failed to add post execution");
            return new ResponseResult(false, ResultType.ADD_ERROR, StatusCode.ADDERROR);
        }
        return new ResponseResult(true, ResultType.OPERATION_SUCCESS, StatusCode.OPERATIONSUCCESS);
    }

    private Position assemblePosition(String positionName,String operatorId){
        Position position = new Position();
        position.setPositionId(UUIDTool.generateUUID());
        position.setPositionName(positionName);
        position.setPositionCreatorAccountId(operatorId);
        return position;
    }

    @Override
    @Transactional
    public ResponseResult insertPositionBatch(String positionNames, String operatorId) {
        if (StringUtils.isBlank(positionNames) || StringUtils.isBlank(operatorId)){
            log.info("The parameter is empty");
            return new ResponseResult(false,ResultType.PARAMETER_NULL, StatusCode.PARAMETERNULL);
        }
        String[] positionNameArray = positionNames.split(",");
        StringBuffer positionNameBuffer = new StringBuffer();
        for(String positionName:positionNameArray){
            if (positionMapper.checkPositionName(positionName) > 0){
                positionNameBuffer.append(positionName+",");
            }
        }
        if (positionNameBuffer.length() > 0){
            log.info("positionName already exists");
            String existPositionNames = positionNameBuffer.substring(0,positionNameBuffer.length()-1);
            return new ResponseResult(existPositionNames,false,"positionName already exists",StatusCode.OPERATIONERROR);
        }
        List<Position> positionList = new ArrayList<>();
        for(String positionName:positionNameArray){
            Position position = assemblePosition(positionName,operatorId);
            positionList.add(position);
        }
        int result = positionMapper.insertPositionBatch(positionList);
        if (result == 0){
            log.info("Batch increase execution failed");
            return new ResponseResult(false, "Batch increase execution failed",StatusCode.OPERATIONERROR);
        }
        return new ResponseResult(true, "Batch increase successful", StatusCode.OPERATIONSUCCESS);
    }

    /**
     * updatePosition: 更新职位信息
     *
     * @param position  职位对象
     * @return  操作成功: {true, "更新成功", 204}
     */
    @Override
    public ResponseResult updatePosition(Position position,String operatorId) {
        if (position == null || StringUtils.isBlank(operatorId)) {
            log.info("The parameter is empty and the job information update failed");
            return new ResponseResult(false, ResultType.PARAMETER_NULL, StatusCode.PARAMETERNULL);
        }
        Position queryPosition = positionMapper.selectByPrimaryKey(position.getPositionId());
        if (queryPosition == null){
            log.info("The position doesn't exist");
            return ResponseResult.resultError("The position doesn't exist");
        }
        position.setPositionUpdatorAccountId(operatorId);
        if (positionMapper.updateByPrimaryKeySelective(position) == 0) {
            log.info("Failed to update position information");
            return new ResponseResult(false, ResultType.UPDATE_ERROR, StatusCode.UPDATEERROR);
        }
        return new ResponseResult(true, ResultType.OPERATION_SUCCESS, StatusCode.OPERATIONSUCCESS);
    }

    /**
     * queryOne: 通过职位ID查询职位信息
     *
     * @param positionId    职位ID
     * @return  操作成功: {position, true, "查询成功", 201}
     */
    @Override
    public ResponseResult queryOne(String positionId) {
        if (StringUtils.isBlank(positionId)) {
            log.info("the parameter is empty");
            return new ResponseResult(false, ResultType.PARAMETER_NULL, StatusCode.PARAMETERNULL);
        }
        Position position = positionMapper.selectByPrimaryKey(positionId);
        if (position == null) {
            log.info("The search for job information failed");
            return new ResponseResult(false, ResultType.FIND_ERROR, StatusCode.FINDERROR);
        }
        return new ResponseResult(position, true, ResultType.OPERATION_SUCCESS, StatusCode.OPERATIONSUCCESS);
    }

    /**
     * queryName: 通过职位ID查询职位名称
     *
     * @param positionId    职位编号
     * @return  {positionName, true, "查询成功", 201}
     */
    @Override
    public ResponseResult queryName(String positionId) {
        if (StringUtils.isBlank(positionId)) {
            log.info("The parameter is empty");
            return new ResponseResult(false, ResultType.PARAMETER_NULL, StatusCode.PARAMETERNULL);
        }
        String positionName = positionMapper.selectPositionNameByPrimaryKey(positionId);
        if (positionName == null) {
            log.info("Failed to query positionName");
            return new ResponseResult(false, ResultType.FIND_ERROR, StatusCode.FINDERROR);
        }
        log.info("positionName query results: " + positionName);
        return new ResponseResult(positionName, true, ResultType.OPERATION_SUCCESS, StatusCode.OPERATIONSUCCESS);
    }

    /**
     * 将数据库数据组装成业务层Vo对象
     * @param position 需要组装的职位对象
     * @return 返回组装好的Vo对象
     */
    private PositionInfoVo assemblePositionListVo(Position position){
        PositionInfoVo positionListVo = new PositionInfoVo();
        positionListVo.setPositionId(position.getPositionId());
        positionListVo.setPositionName(position.getPositionName());
        positionListVo.setPositionCreatorName(accountMapper.selectAccountNameByPrimaryKey(position.getPositionCreatorAccountId()));
        positionListVo.setPositionCreatedTime(DateTool.dateToString(position.getPositionCreatedTime(), DataCommon.YYYY_1MM_1DD_HH_MM_SS));
        positionListVo.setPositionUpdatorName(accountMapper.selectAccountNameByPrimaryKey(position.getPositionUpdatorAccountId()));
        positionListVo.setPositionUpdatedTime(DateTool.dateToString(position.getPositionUpdatedTime(), DataCommon.YYYY_1MM_1DD_HH_MM_SS));
        return positionListVo;
    }

    /**
     * queryAll: 查询所有职位
     *
     * @return  操作成功: {positionList, true, "查询成功", 201}
     */
    @Override
    public ResponseResult queryAllPositionDetail() {
        List<Position> positionList = positionMapper.findAllPosition();
        if (CollectionUtils.isEmpty(positionList)) {
            log.info("No position was found");
            return new ResponseResult(true, "No position was found", StatusCode.FINDNULL);
        }
        List<PositionInfoVo> positionInfoVos = new ArrayList<>(positionList.size());
        for(Position position:positionList){
            PositionInfoVo positionInfoVo = assemblePositionListVo(position);
            positionInfoVos.add(positionInfoVo);
        }
        return new ResponseResult(positionInfoVos, true, ResultType.OPERATION_SUCCESS, StatusCode.OPERATIONSUCCESS);
    }

    @Override
    public ResponseResult queryAllPosition() {
        List<Position> positionList = positionMapper.findAllPosition();
        if (CollectionUtils.isEmpty(positionList)){
            log.info("position is null");
            return ResponseResult.resultSuccess(null,"position is null");
        }
        Map<String,String> positionMap = new HashMap<>();
        for(Position  position:positionList){
            positionMap.put(position.getPositionName(),position.getPositionId());
        }
        return ResponseResult.resultSuccess(positionMap,"search successful");
    }

    /**
     * deletePosition: 通过职位ID删除职位
     *
     * @param positionId    职位ID
     * @return  操作成功: {true, "删除成功", 203}
     */
    @Override
    @Transactional
    public ResponseResult deletePosition(String positionId) {
        if (StringUtils.isBlank(positionId)){
            log.info("The parameter is empty");
            return new ResponseResult(false, ResultType.PARAMETER_NULL,StatusCode.PARAMETERNULL);
        }
        if(positionMapper.checkIsExistEmployee(positionId) > 0){
            if (positionMapper.cascadeUpdateEmployeeByPrimaryKey(positionId,"00000000000000000000000000000001") == 0){
                return new ResponseResult(false,"Employee position update failed", StatusCode.FAULT_FLAG);
            }
        }
        if (positionMapper.deleteByPrimaryKey(positionId) == 0){
            log.info("Position deletion failed to execute");
            return new ResponseResult(false,"Position deletion failed to execute", StatusCode.FAULT_FLAG);
        }
        return new ResponseResult(true,"Delete the success", StatusCode.OPERATIONSUCCESS);
    }

    @Override
    @Transactional
    public ResponseResult deletePositionBatch(String positions) {
        if (StringUtils.isBlank(positions)){
            log.info("Parameter null values");
            return new ResponseResult(false,ResultType.PARAMETER_NULL, StatusCode.PARAMETERNULL);
        }
        String[] positionArray = positions.split(",");
        List<String> positionIds = new ArrayList<>();
        for(String positionId:positionArray){
            if (positionMapper.selectByPrimaryKey(positionId) == null){
                return new ResponseResult(false,"Contains unknown job number", StatusCode.OPERATIONERROR);
            }
            positionIds.add(positionId);
        }
        if (positionMapper.deletePositionBatch(positionIds) == 0){
            log.info("Batch deletion failed");
            return new ResponseResult(false,"Batch deletion failed", StatusCode.OPERATIONERROR);
        }
        return  new ResponseResult(true,"Batch deletion successful",StatusCode.OPERATIONSUCCESS);
    }

}
